package com.dmall.promotion.useraop.listener;

import com.dmall.promotion.useraop.event.UserOperationEvent;
import com.dmall.promotion.useraop.handler.AbsUserOperationHandler;
import com.dmall.promotion.useraop.handler.context.UserOperationHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户操作事件监听器
 * @author xiao1.wang
 * @date 2021-06-03 22:04:29
 */
@Component
@Slf4j
public class UserOperationListener {

    @Resource
    private UserOperationHandlerContext handlerContext;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Async("taskExecutor")
    @EventListener
    public void listenEvent(UserOperationEvent event) {
        try {
            List<AbsUserOperationHandler> syncOrderHandlers = handlerContext.getSyncHandlers(event.getOperation());
            List<AbsUserOperationHandler> asyncOrderHandlers = handlerContext.getAsyncHandlers(event.getOperation());
            for (AbsUserOperationHandler syncOrderHandler : syncOrderHandlers) {
                syncOrderHandler.doOperationLogic(event);
            }
            for (AbsUserOperationHandler asyncOrderHandler : asyncOrderHandlers) {
                taskExecutor.execute(() -> asyncOrderHandler.doOperationLogic(event));
            }
        } catch (Exception e) {
            log.error("UserOperationListener listenEvent...", e);
        }
    }
}
